'use strict';
import React, {Component} from 'react';
import {
    View,
    Image,
    Dimensions,
    TouchableWithoutFeedback,
    StyleSheet,
    Text,
    TouchableOpacity,
    TextInput,
    ScrollView,
    TouchableHighlight,
    TouchableNativeFeedback

} from 'react-native';

import ToastUtil from '../utils/toast-util';
import {uuid} from '../utils/util';
import Http from '../utils/http';
import Color from '../constant/color';

var {Loading, EasyLoading} = require('react-native-easy-loading');
const SmartKeyboard = require('@remobile/react-native-smart-keyboard');

import {NavigationActions} from 'react-navigation'

let winWidth = Dimensions.get('window').width;//屏幕宽度

let winHeight = Dimensions.get('window').height;//屏幕高度
const REMAIN_SECONDS = 60;
let interver1;
let navParams;

export default class ForgetPwdScene extends Component {

    constructor(props) {
        super(props);
        navParams = this.props.navigation.state.params;
        this.state = {
            btn_sendVc_title: '发送验证码',
            btn_sendVc_disabled: false,
            btn_sendVc_backgroundColor: Color.BTN_BGCOLOR,
            btn_sendVc_fontColor: Color.BTN_TEXT,
            loaded: false,
            mobile: navParams.mobile,
            yanzhengma: '',
            password: '',
            rePassword: '',
            remainSeconds: REMAIN_SECONDS,
            bgYanzhengma: '',

        }

        this.btnSendVc_disable.bind(this);
        this.btnSendVc_enable.bind(this);


    }

    componentDidMount() {

        if (this.props.mobile) {  //


        }

        SmartKeyboard.enable();


        this.setState({loaded: true})
    }


    componentWillUnmount() {
        if (interver1) {
            clearInterval(interver1);
        }
        //alert('清除了');


    }


    btnSendVc_disable(btn_sendVc_title) {

        console.info('btnSendVc_disable');

        //过程中禁止再次发送
        this.setState({
            btn_sendVc_disabled: true,
            btn_sendVc_backgroundColor: Color.BTN_DISABLE_BGCOLOR,
            btn_sendVc_fontColor: Color.BTN_DISABLE_TEXT,
            btn_sendVc_title: btn_sendVc_title


        });


    }

    btnSendVc_enable(btn_sendVc_title) {

        //过程中禁止再次发送
        this.setState({
            btn_sendVc_disabled: false,
            btn_sendVc_backgroundColor: Color.BTN_BGCOLOR,
            btn_sendVc_fontColor: Color.BTN_TEXT,
            btn_sendVc_title: btn_sendVc_title

        });


    }


    sendYanzhengma() {








        //检查手机号是否合法

        let checkMobile = this.state.mobile && this.state.mobile.length === 11 && /\d{11}/.test(this.state.mobile);
        if (!checkMobile) {
            alert('手机号不得为空且必须有效');
            return;
        }

        //将手机号记录下来，
        let mobile = this.state.mobile;

        let uu = Util.uuid();
        let params = {
            mobile: this.state.mobile,
            uniqueUserId: uu
        };

        this.btnSendVc_disable('发送中');


        Http.post_upload('sendVerification', null, params)
            .then(res => {

                if (res.returnType.resultCode === '1') {


                    ToastUtil.show("验证码发送成功");
                    console.info('yanzhengma:' + res.returnType.other.yanzhengma);
                    let currentDate = new Date();
                    this.setState({
                        sendYanzhengmaDate: currentDate,
                    });
                    this.setState({bgYanzhengma: res.returnType.other.yanzhengma});

                    this.promise_sendVc().then(() => {
                    }, () => {
                    });
                } else {
                    ToastUtil.show('验证码发送失败' + res.returnType.resultMessage);
                    this.btnSendVc_enable('重新发送');


                }


            }).catch(err => {
            //请求失败
            ToastUtil.show('发送失败，错误信息:' + err);
            this.btnSendVc_enable('重新发送');


        })


    }


    promise_sendVc(resolve, reject) {


        return new Promise((resolve, reject) => {


            interver1 = setInterval(() => {
                //console.info('remainSeconds:'+remainSeconds);
                let remainSecondsNow = this.state.remainSeconds - 1

                if (remainSecondsNow === -1) {


                    clearInterval(interver1);
                    this.btnSendVc_enable('重新获取');
                    this.setState({remainSeconds: REMAIN_SECONDS});


                } else {
                    //  console.warn("seconds:"+remainSecondsNow);
                    this.btnSendVc_disable('已发送:' + remainSecondsNow + '秒');

                    this.setState({remainSeconds: remainSecondsNow});
                }

            }, 1000);


        });

    }

    /* timeout(ms:number){*/
    async timeout(ms) {
        return new Promise((resolve, reject) => {
            setTimeout(() => reject(new Error('Timed out')), ms);
        });
    }


    xiayibu() {



        //检查手机号是否合法

        let checkMobile = this.state.mobile && this.state.mobile.length === 11 && /\d{11}/.test(this.state.mobile);
        if (!checkMobile) {
            alert('手机号不得为空且必须有效');
            return;
        }

        let checkYanzhengMa = this.state.yanzhengma;
        if (!checkYanzhengMa) {
            alert('验证码不得为空');
            return;
        }

        let checkPassword = this.state.password && this.state.password.length >= 8;
        if (!checkPassword) {
            alert('密码不得为空，且长度大于等于8位');
            return;
        }

        let checkRePassword = this.state.rePassword && this.state.rePassword === this.state.password;
        if (!checkRePassword) {
            alert('确认密码必须与密码一致');
            return;
        }


        let currentDate = new Date();
        let checkYangzhengma2 = this.state.yanzhengma && this.state.yanzhengma === this.state.bgYanzhengma
            && this.state.sendYanzhengmaDate && currentDate.getTime() - this.state.sendYanzhengmaDate.getTime() <= 10 * 60 * 1000;
        checkYangzhengma2 = true;   //debug
        if (!checkYangzhengma2) {
            alert('验证码不正确或者超时')
            return;
        }


        Promise.resolve().then(EasyLoading.show('loading...', 5000));


        Http.post_upload('resetPassword', this.state.mobile, {

            newPassword: this.state.password,
            username: this.state.mobile,

        }).then((res) => {
            Promise.resolve().then(EasyLoading.dismis());
            ToastUtil.show(res.returnType.resultMessage);

            if (res.returnType.resultCode === '1') {


                //清空路由
                let resetAction = NavigationActions.reset({
                    index: 0,
                    actions: [
                        NavigationActions.navigate({routeName: 'Login'})//要跳转到的页面名字
                    ]
                });
                this.props.navigation.dispatch(resetAction);


            }
            // this.props.navigation.navigate('Login');

        }).catch((error) => {
            //alert(error);
            ToastUtil.show("报错:" + error);
            Promise.resolve().then(EasyLoading.dismis());


        });


    }


    render() {
        if (!this.state.loaded) {

            return (
                <View>
                    <Text>loading.....</Text>
                </View>
            )
        } else {
            return (

                <ScrollView style={styles.body}>


                    <View style={[styles.input_view, {marginTop: 15}]}>
                        <View style={{flex: 1,}}><Text style={styles.input_label}>手机号</Text></View>
                        <View style={{flex: 3,}}>
                            <TextInput
                                placeholder={'手机号'}
                                placeholderTextColor={'#CCC'}
                                underlineColorAndroid="transparent"
                                value={this.state.mobile}
                                blurOnSubmit={true}
                                onChangeText={(text) => {
                                    this.setState({mobile: text})
                                }}
                            />
                        </View>
                    </View>


                    <View style={styles.input_view}>
                        <View style={{flex: 1,}}><Text style={styles.input_label}>新密码</Text></View>
                        <View style={{flex: 3,}}>
                            <TextInput
                                placeholder={'请输入密码'}
                                blurOnSubmit={true}
                                placeholderTextColor={'#CCC'}
                                underlineColorAndroid="transparent"
                                secureTextEntry={true}
                                autoCapitalize="none"//不自动大写
                                autoCorrect={false} //不自动纠正拼写
                                onChangeText={(text) => {
                                    this.setState({'password': text})
                                }}
                            />
                        </View>
                    </View>


                    <View style={styles.input_view}>
                        <View style={{flex: 1,}}><Text style={styles.input_label}>确认密码</Text></View>
                        <View style={{flex: 3,}}>
                            <TextInput
                                placeholder={'请输入确认密码'}
                                blurOnSubmit={true}
                                placeholderTextColor={'#CCC'}
                                underlineColorAndroid="transparent"
                                secureTextEntry={true}
                                autoCapitalize="none"//不自动大写
                                autoCorrect={false} //不自动纠正拼写
                                onChangeText={(text) => {
                                    this.setState({'rePassword': text})
                                }}
                            />
                        </View>
                    </View>


                    <View style={styles.input_view}>

                        <View style={{flex: 1,}}><Text style={styles.input_label}>验证码</Text></View>

                        <View style={{flex: 3,}}>
                            <TextInput
                                placeholder={'请输入验证码'}
                                blurOnSubmit={true}
                                placeholderTextColor={'#CCC'}
                                underlineColorAndroid="transparent"
                                secureTextEntry={true}
                                autoCapitalize="none"//不自动大写
                                autoCorrect={false} //不自动纠正拼写
                                onChangeText={(text) => {
                                    this.setState({'yanzhengma': text})
                                }}
                            />


                        </View>

                    </View>


                    <View style={[styles.btn, {backgroundColor: this.state.btn_sendVc_backgroundColor}]}>
                        <TouchableHighlight
                            disabled={this.state.btn_sendVc_disabled} onPress={this.sendYanzhengma.bind(this)}
                            style={{flex: 1}}>
                            <Text
                                style={[styles.btn_text, {color: this.state.btn_sendVc_fontColor}]}>{this.state.btn_sendVc_title}</Text>
                        </TouchableHighlight>
                    </View>


                    <View style={styles.btn}>
                        <TouchableHighlight onPress={this.xiayibu.bind(this)} style={{flex: 1}}>
                            <Text style={styles.btn_text}>完成</Text>
                        </TouchableHighlight>
                    </View>


                    <View style={styles.zhushi_view}>
                        <Text style={styles.zhushi_text}>密码至少包含8个字符。</Text>

                    </View>


                </ScrollView>




            )
        }


    }

}


const styles = StyleSheet.create({
    body: {
        backgroundColor: Color.VIEW_BGCOLOR,
        height: winHeight,
        flex: 1,
    },

    zhushi_view: {
        marginLeft: 15, marginRight: 15, marginTop: 15, marginBottom: 0,
        flexDirection: "row", justifyContent: "center",
    },
    zhushi_text: {
        color: Color.TEXT_GREY,
        fontSize: 14,

    },

    input_view: {
        marginLeft: 0,
        marginRight: 0,
        marginTop: 0,
        marginBottom: 0,
        flexDirection: "row",
        justifyContent: "center",
        backgroundColor: "#ffffff",
        borderBottomWidth: 1,
        borderColor: Color.TEXTINPUT_LINE,
        padding: 8
    },
    input_label: {},
    btn: {
        backgroundColor: Color.BTN_BGCOLOR,
        padding: 10,
        margin: 15,
        marginBottom: 0,
        borderRadius: 5,
    }
    ,
    btn_text: {
        alignSelf: 'center', fontSize: 15, color: Color.BTN_TEXT
    }


});

